//
//  StoreStandardView.m
//  Yanwei
//
//  Created by weijunjie on 2018/8/10.
//  Copyright © 2018年 DCloud. All rights reserved.
//

#import "StoreStandardView.h"
#import "GoodsStandardModel.h"
#import "ChooseRank.h"
#import "GoodsModel.h"
#import "MuchStoreRequestManager.h"
#import "AddStoreNumView.h"
#define kFixHeight 196 // 非sku高度
@interface StoreStandardView() <ChooseRankDelegate, AddStoreNumViewDelegate>
@property (nonatomic, strong) UIImageView *goodsImageView;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *seletedStandardLabel;
@property (nonatomic, strong) UIScrollView *standardScrollView;
@property (nonatomic, strong) UIButton *sureBtn;
@property (nonatomic, strong) NSMutableArray *ranks;
@property (nonatomic, strong) NSMutableArray *chooseStandardArray;
@property (nonatomic, copy) NSString *alreadyChooseString;
@property (nonatomic, strong) UIView *closeView;
@property (nonatomic, strong) GoodsModel *standardPreModel;
@property (nonatomic, strong) UILabel *lowBuyNumberLabel; // 最低购买量
@property (nonatomic, strong) AddStoreNumView *storeNumView; // 加减数量

@end
@implementation StoreStandardView

- (void)setStandardModel:(GoodsStandardModel *)standardModel {
    _standardModel = standardModel;
    
    [self disPlayOriginData];
    [self.standardScrollView removeAllSubviews];
    
    // 规格组数
    NSInteger count = standardModel.spuSpecifics.count;
    // 具体规格
    CGFloat maxY = 0;
    CGFloat height = 0;
    self.ranks = [NSMutableArray array];
    for (NSInteger i = 0; i < count; i ++) {
        ChooseRank *rank = [[ChooseRank alloc] initWithFrame:CGRectMake(0, maxY, ScreenWidth, 35) data:standardModel.spuSpecifics[i]];
        maxY = CGRectGetMaxY(rank.frame);
        height += rank.height;
        rank.tag = 100 + i;
        rank.delegate = self;
        [self.standardScrollView addSubview:rank];
        [self.ranks addObject:rank];
    }
    
    ChooseRank *rank = self.ranks.lastObject;
    [self.standardScrollView addSubview:self.storeNumView];
    self.storeNumView.frame = CGRectMake(0, CGRectGetMaxY(rank.frame) + 5, ScreenWidth, 80);
    [self.standardScrollView addSubview:self.lowBuyNumberLabel];
    self.lowBuyNumberLabel.frame = CGRectMake(15, CGRectGetMaxY(self.storeNumView.frame) + 5, ScreenWidth - 15, 17);
    
    CGFloat contentHeight = maxY + 105;
    self.standardScrollView.contentSize = CGSizeMake(0, contentHeight + 20 + 49);
    
    CGFloat maxHeight = ScreenHeight * 2 / 3;
    if (APP.iPhoneType == iPhoneX) {
        height = contentHeight + kFixHeight + 34;
    } else {
        height = contentHeight + kFixHeight;
    }
    if (height > maxHeight) {
        height = maxHeight;
    }
    
    self.height = height;
    
    // 判断是否为单一规格
    NSInteger skuCount = standardModel.spuSpecifics.count;
    if (skuCount == 1) { // 单规格,默认选中
        for (ChooseRank *rank in self.ranks) {
            [rank btnClick:rank.btnView.subviews.firstObject];
        }
    } else {
        NSArray *attrs = [self.goodsModel.selectedStandardName componentsSeparatedByString:@","];

        if (attrs.count != 0) { // 有值则选择了已选规格
            for (NSString *sidStr in attrs) {
                // 选中已选规格项
                for (ChooseRank *rank in self.ranks) {
                    for (UIButton *btn in rank.btnView.subviews) {
                        if ([btn.titleLabel.text isEqualToString:sidStr]) {
                            [rank btnClick:btn];
                            break;
                        }
                    }
                }
            }
        }
    }
    
}

/**
  显示初始数据
     图片: 主图
     价格: sku价格
     规格: 请选择
 */
- (void)disPlayOriginData {
    [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:self.goodsModel.mainImagePath] placeholderImage:NewStoreDefault];
    self.priceLabel.text = [NSString stringWithFormat:@"价格：¥%@",self.goodsModel.sellingPrice];

    self.seletedStandardLabel.text = @"请选择";
}

#pragma mark - 懒加载
- (UILabel *)lowBuyNumberLabel {
    if (!_lowBuyNumberLabel) {
        _lowBuyNumberLabel = [[UILabel alloc] init];
        _lowBuyNumberLabel.font = APPFONT(12);
        _lowBuyNumberLabel.textColor = Color175030;
    }
    return _lowBuyNumberLabel;
}

- (AddStoreNumView *)storeNumView {
    if (!_storeNumView) {
        _storeNumView = [[AddStoreNumView alloc] init];
        _storeNumView.delegate = self;
        _storeNumView.userInteractionEnabled = NO;
    }
    return _storeNumView;
}

- (UIView *)closeView {
    if (!_closeView) {
        
        _closeView = [[UIView alloc] init];
        [self addSubview:_closeView];
        [_closeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self);
            make.width.height.mas_equalTo(50);
        }];
        
        __weakConfigure
        [_closeView tapUpWithBlock:^(UIView *v) {
            [__weakSelf closeAction];
        }];
        
        UIButton *closeBtn = [[UIButton alloc] init];
        [closeBtn setImage:[UIImage imageNamed:@"pop_close"] forState:UIControlStateNormal];
        [_closeView addSubview:closeBtn];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self).offset(20);
            make.right.equalTo(self).offset(-15);
            make.width.height.mas_equalTo(14);
        }];
    }
    return _closeView;
}

- (UIImageView *)goodsImageView {
    if (!_goodsImageView) {
        _goodsImageView = [[UIImageView alloc] init];
        _goodsImageView.layer.borderColor = Color217.CGColor;
        _goodsImageView.layer.borderWidth = 0.5;
        _goodsImageView.layer.cornerRadius = 1;;
        _goodsImageView.layer.masksToBounds = YES;
        [self addSubview:_goodsImageView];
        [_goodsImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(15);
            make.top.equalTo(self.closeView).offset(20);
            make.width.height.mas_equalTo(88);
        }];
    }
    return _goodsImageView;
}

- (UILabel *)priceLabel {
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc] init];
        _priceLabel.font = APPFONT(16);
        _priceLabel.textColor = Color175030;
        [self addSubview:_priceLabel];
        [_priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.goodsImageView.mas_right).offset(8);
            make.bottom.equalTo(self.seletedStandardLabel.mas_top).offset(-5);
        }];
    }
    return _priceLabel;
}

- (UILabel *)seletedStandardLabel {
    if (!_seletedStandardLabel) {
        _seletedStandardLabel = [[UILabel alloc] init];
        _seletedStandardLabel.font = APPFONT(15);
        _seletedStandardLabel.textColor = Color34;
        _seletedStandardLabel.numberOfLines = 2;
        [self addSubview:_seletedStandardLabel];
        [_seletedStandardLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.goodsImageView.mas_right).offset(8);
            make.right.equalTo(self);
            make.bottom.equalTo(self.goodsImageView);
        }];
    }
    return _seletedStandardLabel;
}

- (UIScrollView *)standardScrollView {
    if (!_standardScrollView) {
        _standardScrollView = [[UIScrollView alloc] init];
        [self addSubview:_standardScrollView];
        [_standardScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.sureBtn);
            make.top.equalTo(self.goodsImageView.mas_bottom).offset(19);
        }];
    }
    return _standardScrollView;
}

- (UIButton *)sureBtn {
    if (!_sureBtn) {
        _sureBtn = [[UIButton alloc] init];
        [_sureBtn setTitle:@"确 定" forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sureBtn setBackgroundColor:Color175030];
        [self addSubview:_sureBtn];
        [_sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.height.mas_equalTo(49);
            if (APP.iPhoneType == iPhoneX) {
                make.bottom.equalTo(self).offset(-34);
            } else {
                make.bottom.equalTo(self);
            }
        }];
        [_sureBtn addTarget:self action:@selector(sureBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

- (NSMutableArray *)chooseStandardArray {
    if (!_chooseStandardArray) {
        _chooseStandardArray = [NSMutableArray array];
        NSInteger count = self.standardModel.spuSpecifics.count; //  总规格组
        for (int i = 0; i < count; i++) {
            [_chooseStandardArray addObject:[NSNull null]];
        }
    }
    return _chooseStandardArray;
}

#pragma mark - ChooseRankDelegate
/** 选择规格 */
- (void)selectStandardBtn:(UIButton *)selectBtn goodsStandardModel:(GoodsStandardModel *)model headerValue:(NSString *)headerValue {
    
    [self.standardModel.spuSpecifics enumerateObjectsUsingBlock:^(GoodsStandardModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.value isEqualToString:headerValue]) {
            self.chooseStandardArray[obj.rank - 1] = model.sid;
            *stop = YES;
        }
    }];
    
    // 某组没选择直接返回
    if ([self.chooseStandardArray containsObject:[NSNull null]]) return;
    // 判断数组没有空数据则匹配获取skusid
    __weakConfigure
    self.standardModel.seletedSkuSid = @"";
    NSString *sidStr = [self.chooseStandardArray componentsJoinedByString:@"|"];
    
    [self.standardModel.itemSkuList enumerateObjectsUsingBlock:^(GoodsStandardModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([sidStr isEqualToString:obj.specificCode]) {
            [__weakSelf updataGoodsDetailInfo:obj];
            *stop = YES;
        }
    }];
}

#pragma mark - AddStoreNumViewDelegate
- (void)didSelectedReduceNumOrAddButton:(NSString *)storeNum {
    NSInteger inventoryCount = self.goodsModel.inventoryCount; // 库存量
    if ([storeNum integerValue] >= inventoryCount) { // 超过库存量
        [self.storeNumView changeAddNumButtonColor:YES];
        self.goodsModel.number = inventoryCount;
        self.storeNumView.numTextField.text = [NSString stringWithFormat:@"%@",@(inventoryCount)]; // 最低购买量
    } else if ([storeNum integerValue] <= self.goodsModel.minCount) { // 低于限购数量
        [self.storeNumView changeReduceNumButtonColor:YES];
        self.goodsModel.number = self.goodsModel.minCount;
        self.storeNumView.numTextField.text = [NSString stringWithFormat:@"%@",@(self.goodsModel.minCount)]; // 最低购买量
    } else {
        self.goodsModel.number = storeNum.integerValue;
    }
    
}

- (void)closeAction {
    [self.alertController dismissViewControllerAnimated:YES];
}

- (void)updataGoodsDetailInfo:(GoodsStandardModel *)model {
    self.storeNumView.userInteractionEnabled = YES;
    self.seletedStandardLabel.text = [NSString stringWithFormat:@"已选择%@",model.value];
    [self.goodsImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePath] placeholderImage:NewStoreDefault];

    self.goodsModel.sellingPrice = model.sellingPrice;
    self.goodsModel.memberPrice = model.memberPrice;
    self.goodsModel.employeePrice = model.employeePrice;
    self.goodsModel.sellingDiscount = model.sellingDiscount;
    self.goodsModel.memberDiscount = model.memberDiscount;
    self.goodsModel.employeeDiscount = model.employeeDiscount;
    self.goodsModel.selectedSkuSid = model.skuSid;
    self.goodsModel.selectedStandardName = model.value;
    self.goodsModel.inventoryCount = model.inventoryCount;
    self.goodsModel.minCount = model.minCount;
    
    
    self.storeNumView.inventory = [NSString stringWithFormat:@"%@",@(model.inventoryCount)]; // 库存
    NSInteger minCount = model.minCount;
    if (minCount <= 1) {
        minCount = 1;
    }
    self.storeNumView.numTextField.text = [NSString stringWithFormat:@"%@",@(minCount)]; // 最低购买量
    [self.storeNumView changeReduceNumButtonColor:YES]; // 减号按钮置灰
    
    if (model.minCount > 1) { // 起够数大于1需要提示
        self.lowBuyNumberLabel.hidden = NO;
        self.lowBuyNumberLabel.text = [NSString stringWithFormat:@"该商品起购数量为%@",@(model.minCount)];
    } else {
        self.lowBuyNumberLabel.hidden = YES;
        self.lowBuyNumberLabel.text = nil;
    }
    
    
    // 更新商品详情
    if (self.updateStoreDetailInfoBlock) {
        self.updateStoreDetailInfoBlock();
    }
}

// 确定购买
- (void)sureBtnAction {
    
    if ([self.seletedStandardLabel.text isEqualToString:@"请选择"] || !self.goodsModel.selectedSkuSid.hasValue) {
        jxt_showAlertMessage(@"请选择规格");
        return;
    }
    
    jxt_showAlertMessage(@"敬请期待!!!");
}

@end
